package com.example.zbh.dsliao.ui.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.db.entity.SongRecommend;
import com.example.zbh.dsliao.utils.net.VolleySingleton;

import java.util.List;

/**
 * Created by yaolin on 15/11/21.
 */
public class RVSongRecommendAdapter extends RecyclerView.Adapter<RVSongRecommendAdapter.MyViewHolder>{
    private List<SongRecommend> datas;
    private Context context;

    VolleySingleton volleySingleton = VolleySingleton.getInstance();
    private ImageLoader imageLoader;

    public RVSongRecommendAdapter(Context context) {
        this.context = context;
        imageLoader = volleySingleton.getImageLoader();
    }

    public void addData(List<SongRecommend> datas){
        this.datas = datas;
        notifyDataSetChanged();
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.list_song_recommend, null);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        if (datas != null && datas.size() > 0){
            SongRecommend s = datas.get(position);
            holder.song.setText(s.getTitle() + "-" + s.getAuthor());
            holder.reason.setText(s.getRecommend_reason());
            if(s.getPic_big() != null){
                String imgUrl = s.getPic_big();
                getBitmap(imgUrl, holder.img);

            }
        }

    }

    private void getBitmap(String url, NetworkImageView imageView) {
        imageView.setDefaultImageResId(R.mipmap.music_cache_icon);
        imageView.setErrorImageResId(R.mipmap.music_cache_icon);
        imageView.setImageUrl(url, imageLoader);
    }

    @Override
    public int getItemCount() {
        return datas != null && datas.size() > 0 ? datas.size() : 0;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        private NetworkImageView img;
        private TextView song, reason;

        public MyViewHolder(View itemView) {
            super(itemView);

            img = (NetworkImageView) itemView.findViewById(R.id.img);
            song = (TextView) itemView.findViewById(R.id.song);
            reason = (TextView) itemView.findViewById(R.id.reason);
        }
    }
}
